package com.lagou.register;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.I0Itec.zkclient.ZkClient;

import com.alibaba.fastjson.JSON;
import com.lagou.handler.UserClientHandler;
import com.lagou.request.JSONSerializer;
import com.lagou.request.RpcEncoder;
import com.lagou.request.RpcNode;
import com.lagou.request.RpcRequest;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class ServiceRegister {

    private static Map<String, UserClientHandler> serviceMap = new HashMap<>();

    private static final String ZK_ROOT_PATH = "/rpc-provider";
    private static final String SERVER_STRING = "127.0.0.1:2181";

    public static UserClientHandler getUserClientHandler() {
        Set<String> keySet = serviceMap.keySet();
        UserClientHandler userClientHandler;
        for (String key : serviceMap.keySet()) {
            System.out.println(key);
            return serviceMap.get(key);
        }

        return null;
    }

    public static void initClient() throws InterruptedException {
        // 1）获取zookeeper节点
        ZkClient zkClient = new ZkClient(SERVER_STRING);
        List<String> zkClientChildren = zkClient.getChildren(ZK_ROOT_PATH);

        // 2）遍历子节点
        for (String node : zkClientChildren) {
            String data = zkClient.readData(ZK_ROOT_PATH + "/" + node);
            RpcNode rpcNode = JSON.parseObject(data.getBytes(), RpcNode.class);

            // 3) 初始化UserClientHandler
            UserClientHandler userClientHandler = new UserClientHandler();
            userClientHandler.setRpcNode(rpcNode);
            // 4)创建连接池对象
            EventLoopGroup group = new NioEventLoopGroup();
            // 5)创建客户端的引导对象
            Bootstrap bootstrap = new Bootstrap();
            // 6)配置启动引导对象
            bootstrap.group(group)
                // 设置通道为NIO
                .channel(NioSocketChannel.class)
                // 设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                // 监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        // 添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
            bootstrap.connect(rpcNode.getIp(), rpcNode.getPort()).sync();
            serviceMap.put(data, userClientHandler);
        }

    }

}
